<!DOCTYPE html>
<html>
<head>
  <style>
    .root {
        width: 100%;
        content-visibility: auto;
        padding: 5px;
    }
    .child {
        border: 1px solid black;
        height: 10px;
        width: 10px;
        margin: -1px;
        display: inline-block;
    }
    .active {
        content-visibility: visible;
    }
    #container {
      height: 100px;
      overflow: scroll;
    }
    .spacer {
      height: 3000px;
      width: 10px;
      background: lightblue;
    }
  </style>
  <script src="../resources/runner.js"></script>
</head>
<body>
<div id="container"></div>
</body>

<script>

var isDone = false;
var startTime;
var container = document.getElementById('container');

function runTest() {
  if (startTime) {
    PerfTestRunner.measureValueAsync(PerfTestRunner.now() - startTime);
    PerfTestRunner.addRunTestEndMarker();
  }
  if (!isDone) {
    PerfTestRunner.addRunTestStartMarker();
    startTime = PerfTestRunner.now();

    // We need a spacer since we don't want auto to automatically activate.
    container.innerHTML = '<div class=spacer></div>';

    generateAllContent();

    setTimeout(toggleContentVisibility, 10);

    // Re-run the same test.
    // Wait to allow the asynchronous accessibility code that's
    // covered by traceEventsToMeasure to have a chance to run.
    setTimeout(runTest, 1500);
  }
}

function generateAllContent() {
  const root1 = container.appendChild(document.createElement('div'));
  root1.id = 'root1';
  root1.className = 'root active';

  const root2 = container.appendChild(document.createElement('div'));
  root2.id = 'root2';
  root2.className = 'root';

  for (let i = 0; i < 50; i++) {
    const child1 = generateNodes(100, "blue");
    root1.appendChild(child1);
    const child2 = generateNodes(100, "green");
    root2.appendChild(child2);
  }
}

// Recursively add layers of descendants.
function generateNodes(depth, color) {
  if (depth === 0)
    return;

  const node = document.createElement("div");
  node.className = "child";
  node.style.backgroundColor = color;
  node.setAttribute("tabindex", 0);
  depth--;
  const child = generateNodes(depth, color);
  if(child) {
    node.appendChild(child);
  }
  return node;
}

function toggleContentVisibility(text) {
  // Toggle once.
  document.getElementById("root1").classList.toggle("active");
  document.getElementById("root2").classList.toggle("active");
}

PerfTestRunner.startMeasureValuesAsync({
  description: 'Test accessibility performance when toggling content-visibility:auto/visible on large subtrees.',
  unit: 'ms',
  done: function () {
    isDone = true;
  },
  run: function() {
    runTest();
  },
  iterationCount: 6,
  tracingCategories: 'accessibility',
  traceEventsToMeasure: [
    'ProcessDeferredAccessibilityEvents',
    'RenderAccessibilityImpl::SendPendingAccessibilityEvents'
  ]
});
</script>

</html>
